package org.example.demo1.servlets.ManagePage;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.UserDao;
import org.example.demo1.DAO.RoleDao;
import org.example.demo1.DAO.UserRoleDao;
import org.example.demo1.Entity.User;
import org.example.demo1.Entity.Role;
import org.example.demo1.utils.MybatisUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "UserRoleServlet", urlPatterns = "/API/user/role", loadOnStartup = 1)
public class UserRoleServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        // 获取分页参数
        int pageNum = 1;
        int pageSize = 5; // 每页5条数据

        try {
            // 获取请求中的分页参数
            String pageNumStr = req.getParameter("pageNum");
            if (pageNumStr != null && !pageNumStr.isEmpty()) {
                pageNum = Integer.parseInt(pageNumStr);
            }

            // 获取查询条件
            String username = req.getParameter("username");
            String roleId = req.getParameter("roleId");

            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;

            // 查询数据库
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            RoleDao roleDao = sqlSession.getMapper(RoleDao.class);
            UserRoleDao userRoleDao = sqlSession.getMapper(UserRoleDao.class);

            try {
                // 构建查询结果
                List<Map<String, Object>> resultList = new ArrayList<>();

                // 构建查询参数
                Map<String, Object> params = new HashMap<>();
                params.put("offset", offset);
                params.put("pageSize", pageSize);

                if (username != null && !username.isEmpty()) {
                    params.put("username", "%" + username + "%");
                }

                // 如果指定了角色ID，直接查询该角色下的用户
                if (roleId != null && !roleId.isEmpty()) {
                    params.put("roleId", Integer.parseInt(roleId));
                }

                // 查询用户及其角色信息
                List<User> users;
                int total = 0;


                // 否则查询所有用户
                users = userDao.getUserListPagination(params);
                total = userDao.getUserCount(params);


                // 查询每个用户的角色信息
                for (User user : users) {
                    Map<String, Object> userRoleMap = new HashMap<>();
                    userRoleMap.put("user_id", user.getUser_id());
                    userRoleMap.put("username", user.getUsername());

                    // 获取用户的角色列表
                    List<Integer> roleIds = userRoleDao.getRoleIdsByUserId(user.getUser_id());
                    List<Role> roles = new ArrayList<>();
                    for (Integer rid : roleIds) {
                        Role role = roleDao.getRoleById(rid);
                        if (role != null) {
                            roles.add(role);
                        }
                    }
                    userRoleMap.put("roles", roles);
                    resultList.add(userRoleMap);
                }

                // 构建响应数据
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("msg", "查询成功");
                result.put("total", total);
                result.put("rows", resultList);

                // 返回JSON数据
                out.write(new Gson().toJson(result));
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            // 处理异常
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "查询失败：" + e.getMessage());

            out.write(new Gson().toJson(result));
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        try {
            // 获取请求参数
            int userId = Integer.parseInt(req.getParameter("userId"));
            String[] roleIds = req.getParameterValues("roleIds[]");
            if (roleIds == null) {
                roleIds = req.getParameterValues("roleIds");
            }

            // 获取数据库连接
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserRoleDao userRoleDao = sqlSession.getMapper(UserRoleDao.class);

            try {
                // 删除用户原有的所有角色
                userRoleDao.deleteRolesByUserId(userId);

                // 添加新的角色
                if (roleIds != null) {
                    for (String roleId : roleIds) {
                        userRoleDao.insertUserRole(userId, Integer.parseInt(roleId));
                    }
                }

                // 提交事务
                sqlSession.commit();

                // 返回成功响应
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("msg", "角色更新成功");
                out.write(new Gson().toJson(result));
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            // 处理异常
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "角色更新失败：" + e.getMessage());

            out.write(new Gson().toJson(result));
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
}
